package cj.web.admin.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.web.admin.constants.Constants;
import cj.web.admin.dao.GoodsDAO;
import cj.web.admin.domain.Goods;
import cj.web.admin.utils.Base64;
import cj.web.admin.utils.DecimalCalculateUtil;
import cj.web.admin.utils.ReadConfigProperties;
import cj.web.admin.utils.ReturnUUID;
import cj.web.login.controllers.BaseController;

@Path("/goods")
public class GoodsController extends BaseController{

	private static Logger logger = Logger.getLogger(GoodsController.class.getName());
	
	private final String[] headers = {"商品id","商品名称","商品主图","商品详情页链接地址","商品一级类目","淘宝客链接","商品价格(单位：元)","商品月销量","收入比率(%)",
			"佣金","卖家旺旺","卖家id","店铺名称","平台类型","优惠券id","优惠券总量","优惠券剩余量","优惠券面额","优惠券开始时间",
			"优惠券结束时间","优惠券链接","商品优惠券推广链接"};
	
	@Autowired
	private GoodsDAO goodsDao;
	
	/**
	 * 查询页面
	 * @param model
	 * @param goods
	 * @return
	 */
	@Get("show")
	public String show(Model model,Goods goods) {
		return "/views/goods/goodsList.vm";
	}

	/**
	 * 查询方法
	 * @param goods
	 * @return
	 */
	@Post("getList")
	public String queryList(Goods goods) {
		//当前页  
		goods.setStart((goods.getPage()-1)*goods.getRows());
		goods.setLength(goods.getRows());
		
		List<Goods> arr = goodsDao.query(goods);
		for(Goods obj : arr){
			obj.setCouponUrl(Base64.getFromBase64(obj.getCouponUrl()));
			obj.setTkUrl(Base64.getFromBase64(obj.getTkUrl()));
			obj.setGoodsCouponUrl(Base64.getFromBase64(obj.getGoodsCouponUrl()));
		}

		JSONObject jo = new JSONObject();

		int size = goodsDao.querySize(goods);

		jo.put("rows", arr);
		jo.put("total", size);

		return "@" + jo.toString();
	}
	
	/**
	 * 删除
	 * @param model
	 * @param Ids
	 * @return
	 */
	@Get("deleteById")
	public String deleteById(Model model,@Param("Ids") String Ids) {
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(","))
		{
			goodsDao.deleteById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 导入页面
	 * @param model
	 * @param request
	 * @return
	 */
	@Get("showImport")
	public String showImport(Model model,HttpServletRequest request) {
		//权限设置读取配置的公司组权限
		return "/views/goods/goodsImport.vm";
	}
	
	/**
	 * 导入
	 * @param model
	 * @param xls
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@Post("xlsInput")
	public String xlsInput(Model model, @Param("xlsFile")MultipartFile xls,HttpServletRequest request) throws FileNotFoundException, IOException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
		if (xls != null && !xls.isEmpty()) {
			String orgName = xls.getOriginalFilename();
			String ext =  ReturnUUID.getFileExt(orgName);
			if( ext != null && ext.equals(".xls")){
            	//文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadExcelFilePath");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(orgName);
                //转存文件  
                File tmpXls = new File(path+"/"+fileName);
                xls.transferTo(tmpXls);
                //处理excel文件
                jo = operateXls(tmpXls,request);
			}
			else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2); //文件不是excel
			}
        }
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_1); //文件不存在
		}

		return "@" + jo.toString();
	}
	
	/**
	 * 导入Excel
	 * @param tmpXls
	 * @param companyGroup
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private JSONObject operateXls(File tmpXls,HttpServletRequest request) throws FileNotFoundException, IOException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		//获取工作簿
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(tmpXls));
		//获取sheet页
		HSSFSheet sheet = workbook.getSheetAt(0);
		
		//获取标题行
		HSSFRow titles = sheet.getRow(0);
		if(titles.getPhysicalNumberOfCells() != headers.length){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_3);     //请按照Excel模版导入数据
			return jo;
		}
		String wrongTitles = "",rightTitles="";
		for( int col= 0; col < titles.getPhysicalNumberOfCells(); col++ ){
			String title = titles.getCell(col).getStringCellValue();
			if(!title.equals(headers[col])){
				wrongTitles += title + " ";
				rightTitles += headers[col] + " ";
			}
		}
		if(!"".equals(wrongTitles)){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_4);     //导入表表头错误
			jo.put("wrongTitles", wrongTitles);
			jo.put("rightTitles", rightTitles);
			return jo;
		}
		
		/*------判断订单中数据正确性 START------*/
		//人员列表
		List<Goods> goodslis = new ArrayList<Goods>();
		//导入Excel行数
		int rowNum = sheet.getLastRowNum();
		
		for(int rowIndex = 1; rowIndex <= rowNum; rowIndex++){
			//人员对象
			Goods obj= new Goods();
			//Excel行值
			HSSFRow row = sheet.getRow(rowIndex);
			
			/*
			 * "商品id","商品名称","商品主图","商品详情页链接地址","商品一级类目","淘宝客链接","商品价格(单位：元)",
			 * "商品月销量","收入比率(%)","佣金","卖家旺旺","卖家id","店铺名称","平台类型","优惠券id","优惠券总量",
			 * "优惠券剩余量","优惠券面额","优惠券开始时间","优惠券结束时间","优惠券链接","商品优惠券推广链接"
			 */
			
			obj.setId(returnCellValue(row, 0));//"商品id"
			obj.setName(returnCellValue(row, 1));//"商品名称"
			obj.setImages(Base64.getBase64(returnCellValue(row, 2)));//"商品主图"
			obj.setDetailUrl(Base64.getBase64(returnCellValue(row, 3)));//"商品详情页链接地址"
			obj.setCategory(returnCellValue(row, 4));//"商品一级类目"
			obj.setTkUrl(Base64.getBase64(returnCellValue(row, 5)));//"淘宝客链接"
			String goodsPrice = returnCellValue(row, 6);
			obj.setGoodsPrice(goodsPrice);//"商品价格(单位：元)"
			obj.setSellCount(returnCellValue(row, 7));//"商品月销量"
			obj.setPercentage(returnCellValue(row, 8));//"收入比率(%)"
			obj.setBrokerage(returnCellValue(row, 9));//"佣金"
			obj.setSellww(returnCellValue(row, 10));//"卖家旺旺"
			obj.setSellId(returnCellValue(row, 11));//"卖家id"
			obj.setSellName(returnCellValue(row, 12));//"店铺名称"
			obj.setType(returnCellValue(row, 13));//"平台类型"
			obj.setCouponId(returnCellValue(row, 14));//"优惠券id"
			obj.setCouponCount(returnCellValue(row, 15));//"优惠券总量"
			obj.setCouponSurplus(returnCellValue(row, 16));//"优惠券剩余量"
			String couponDescs = returnCellValue(row, 17);
			obj.setCouponDescs(couponDescs);//"优惠券面额"
			obj.setCouponStartAt(returnCellValue(row, 18));//"优惠券开始时间"
			obj.setCouponEndAt(returnCellValue(row, 19));//"优惠券结束时间"
			obj.setCouponUrl(Base64.getBase64(returnCellValue(row, 20)));//"优惠券链接"
			obj.setGoodsCouponUrl(Base64.getBase64(returnCellValue(row, 21)));//"商品优惠券推广链接"
			obj.setCreateUser(returnSessionObj(request).getAccount());
			obj.setUpdateUser(returnSessionObj(request).getAccount());
			obj.setCouponPrice(returnCouponPrice(goodsPrice, couponDescs));//"商品优惠价"
			goodslis.add(obj);
		}
		
		//循环插入人员基本信息
		for(Goods obj:goodslis){
			try {
				int count = goodsDao.querySizeById(obj.getId());
				if(count!=0){
					goodsDao.update(obj);
				}else{
					goodsDao.create(obj);
				}
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				continue;
			}
		}
		
		return jo;
	}
	
	/**
	 * 返回导入Excel单元值
	 * @param row
	 * @param cellnum
	 * @return
	 */
	private String returnCellValue(HSSFRow row,int cellnum){
		String value = "";
		try {
			HSSFCell orderNoCell = row.getCell(cellnum);
			if(orderNoCell != null){
				orderNoCell.setCellType(Cell.CELL_TYPE_STRING);
				value = orderNoCell.getStringCellValue().toString();
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return value;
		}
		return value;
	}
	
	/**
	 * 返回优惠价格
	 * @param couponDescs
	 * @return
	 */
	private static String returnCouponPrice(String goodsPrice,String couponDescs){
		int couponPrice = 0;
		
		String regEx="[^0-9]";   
		Pattern p = Pattern.compile(regEx);   
		Matcher m = p.matcher(couponDescs);   
		String ss = m.replaceAll(";").trim();
		
		List<String> arr = new ArrayList<String>();
		String[] str1 = ss.split(";");
		for(int i=0;i<str1.length;i++){
			if("".equals(str1[i])){
				continue;
			}else{
				arr.add(str1[i]);
				couponPrice=Integer.valueOf(str1[i]).intValue();
			}
		}
		double returnCouponPrice = DecimalCalculateUtil.sub(Double.parseDouble(goodsPrice), couponPrice);
		if(returnCouponPrice<0)
		{
			return goodsPrice;
		}
		return String.valueOf(returnCouponPrice);
	}
	
	public static void main(String[] args){
		System.out.println(returnCouponPrice("29.80", "满29元减15元"));
	}
}